﻿var gStatInvoke = new Object();
var StatBiz = function (rHd) {
    var __hd = (typeof (rHd) == "string") ? rHd : "statBiz";
    var __gridData = null;
    var __statData = null;
    var __xmlData = null;
    var __formData = null;
    var __formBoxId = null;
    var __formBox = null;
    var __gridBoxId = null;
    var __gridBox = null;

    var __statKey = null;

    var __chartHd = null;
    var __chartFileName = null;
    var __chartPath = null;
    var __chartId = null;
    var __chartPlayerId = null;

    var __chartWidth = 700;
    this.setChartWidth = function (v) {
        __chartWidth = v;
    }

    var __chartHeight = 300;
    this.setChartHeight = function (v) {
        __chartHeight = v;
    }

    var __requestHandler = "admin/module/stat/_Stat.aspx";
    this.setRequestHandler = function (v) {
        __requestHandler = v;
    };

    var __params = null;
    this.setParams = function (rParamJson) {
        __params = rParamJson;
    };
    var __INVOKE = function (rClass, rParams, rFuncs) {
        this.iclass = rClass;
        this.iparams = rParams;
        this.ifuncs = rFuncs;
    };
    var __invokeList = new Array();

    var __displayChart = function () {
        __chartHd = new FusionCharts(__chartPath, __chartId, __chartWidth, __chartHeight, "0", "0");
        __chartHd.setDataXML(__xmlData);
        __chartHd.render(__chartPlayerId);
    };

    var __msgFunc = function (rContent) {
        //alert(rContent);
        rContent = rContent.replace(/\$n/gi, "<br/>");
        jskitBulter.msg.show({
            "Title": "INFO",
            "Content": rContent,
            "RefUrl": null,
            "Redirect": null,
            "Mode": "alert",
            "CallBack": null
        });
    };

    var __ajax = null;
    var __loadFormData = function () {
        var _url = __requestHandler + "?adm=" + jskitUtil.guid() + "&act=form&stat=" + __statKey;
        __ajax = new JskitXmlHttpAction(_url, __hd + ".__loadFormDataCallback", "text");
    };
    this.__loadFormDataCallback = function (json) {
        try {
            eval("__formData = " + json + ";");
        } catch (e) {
            __msgFunc("Load Form Data Exception:\n" + e.message);
            return;
        }
        if (__formData.ex != null) {
            __msgFunc(__formData.ex);
            return;
        }
        try {
            __buildForm();
        } catch (e) {
            __msgFunc("Build Form Html Exception:\n" + e.message);
            return;
        }
        __loadStatData();
    };


    var __loadStatData = function () {
        var _url = __requestHandler + "?adm=" + jskitUtil.guid() + "&act=stat&stat=" + __statKey + __getParamsValueStr();
        __ajax = new JskitXmlHttpAction(_url, __hd + ".__loadStatDataCallback", "text");
    };

    this.__loadStatDataCallback = function (json) {
        try {
            eval("__statData = " + json + ";");
        } catch (e) {
            __msgFunc("Load Stat Data Exception:\n" + e.message);
            return;
        }
        if (__statData.ex != null) {
            __msgFunc(__statData.ex);
            return;
        }

        __xmlData = __statData.xmldata;
        __gridData = __statData.griddata;
        try {
            __displayChart();
        } catch (e) {
            __msgFunc("Display Chart Exception:\n" + e.message);
        }
        try {
            __buildGrid();
        } catch (e) {
            __msgFunc("Build Grid Exception:\n" + e.message);
        }
    };

    var __buildGrid = function () {
        var _str = new Array();
        var _grid = null;
        var _header = null;
        var _body = null;
        var _footer = null;
        var _row = null;
        var _sum = new Array();
        for (var i = 0; i < __gridData.length; i++) {
            _grid = __gridData[i];

            _str.push('<div class="StatGridTitle">' + _grid.title + '</div>');
            _str.push('<table cellspacing="0" cellpadding="0" class="StatGridView">');

            _header = _grid.header;
            _str.push('<tr class="StatGridViewHeader">');
            _str.push('<th>&nbsp;</th>');
            for (var h = 0; h < _header.length; h++) {
                _str.push('<th>' + _header[h].caption + '</th>');
                _sum[h] = 0;
            }
            _str.push('</tr>');

            _body = _grid.body;
            var _cost = 0;
            for (var r = 0; r < _body.length; r++) {
                _row = _grid.body[r];
                _str.push('<tr class="StatGridViewRow">');
                _str.push('<td>' + (r + 1) + '</td>');
                _cost = 0;
                for (var c = 0; c < _row.length; c++) {
                    _str.push('<td>' + _row[c] + '</td>');
                    if (_header[c] != null && _header[c].sum == 1) {
                        _cost = (isNaN(parseFloat(_row[c]))) ? 0 : parseFloat(_row[c]);
                        _sum[c] += _cost;
                    }
                }
                _row = null;
                _str.push('</tr>');
            }
            _cost = null;
            _str.push('<tr class="StatGridViewFooter">');
            _str.push('<td>' + unescape("%u2211") + '</td>');
            for (var h = 0; h < _header.length; h++) {
                if (_header[h].sum == 1) {
                    _str.push('<td>' + _sum[h] + '</td>');
                } else {
                    _str.push('<td>&nbsp;</td>');
                }
            }
            _str.push('</tr>');

            _str.push('</table>');
            _header = null;
            _body = null;
            _footer = null;
            _grid = null;
        }
        __gridBox.innerHTML = _str.join('');
        _str = null;
    };

    var __getParamsValueStr = function () {
        var _obj = null;
        var _str = "";
        if (__params != null) {
            for (var i = 0; i < __params.length; i++) {
                _str += "&" + __params[i].key + "=" + encodeURI(__params[i].value);
            }
        } else {
            for (var i = 0; i < __formData.length; i++) {
                _obj = $("#" + __formData[i].key);
                if (_obj != null) {
                    _str += "&" + __formData[i].key + "=" + encodeURI(_obj.value);
                } else {
                    //alert(__formData[i].key);
                }
            }
        }
        return _str;
    };

    var __buildForm = function () {
        var _str = new Array();
        var _item = null;
        var _id_name = null;
        for (var i = 0; i < __formData.length; i++) {
            _item = __formData[i];
            if (_item.type == "operator") { continue; }
            _id_name = ' id="' + _item.key + '" name="' + _item.key + '" ';
            _str.push('<div class="stat_form_item">');
            _str.push('<span>' + _item.label + unescape("%uFF1A") + '</span>');
            if (_item.type == "input") {
                _str.push('<input ' + _id_name + ' type="text" value="' + _item.def + '" />');
            } else if (_item.type == "datetime") {
                _str.push('<input ' + _id_name + ' size="18" type="text" value="' + _item.def + '" onclick="jskitDateSelector.openMode(this,event,\'dt\');" />');
            } else if (_item.type == "date") {
                _str.push('<input ' + _id_name + ' size="10" type="text" value="' + _item.def + '" onclick="jskitDateSelector.openMode(this,event,\'d\');"  />');
            } else if (_item.type == "year") {
                _str.push(__pushDdlItem(_item, 2000, 2050));
            } else if (_item.type == "month") {
                _str.push(__pushDdlItem(_item, 1, 12));
            } else if (_item.type == "week") {
                _str.push(__pushDdlItem(_item, 1, 54));
            } else if (_item.type == "item") {
                _str.push(__pushRDdlItem(_item, "Ws/_Item.aspx?act=list&ck=" + _item.catKey));
            } else if (_item.type == "user") {
                _str.push(__pushRDdlItem(_item, "Ws/_User.aspx?mode=rddl"));
            } else if (_item.type == "dept") {
                _str.push(__pushRDdlItem(_item, "Ws/_Dept.aspx"));
            } else if (_item.type == "operator") {
                //do nothing
            } else {
                //alert(_item.type);
            }
            _str.push('</div>');
        }
        if (__formData.length > 0) {
            _str.push('<div class="stat_form_item">');
            _str.push('<button onclick="return ' + __hd + '.reLoad();return false;" class="action_btn">' + unescape("%u5237%u65B0%u7EDF%u8BA1") + '</button>');
            _str.push('</div>');
        }
        __formBox.innerHTML = _str.join('');
        __invokeFire();
        _str = null;
    };

    var __pushDdlItem = function (rItem, rMin, rMax) {
        var _str = new Array();
        _str.push('<select id="' + rItem.key + '" name="' + rItem.key + '" >');
        for (var j = rMin; j <= rMax; j++) {
            if (j == parseInt(rItem.def)) {
                _str.push('<option value="' + j + '" selected="selected">' + j + '</option>');
            } else {
                _str.push('<option value="' + j + '">' + j + '</option>');
            }
        }
        _str.push('</select>');
        return _str.join('');
    };
    var __pushRDdlItem = function (rItem, rUrl) {
        var _str = '<input id="' + rItem.key + '1" size="20" type="text" value="' + rItem.defName + '" />';
        _str += '<input id="' + rItem.key + '" name="' + rItem.key + '" type="hidden" value="' + rItem.def + '" />';
        __invokeList.push(new __INVOKE("JskitRichDropDownList", null,
                    [
                        ["deploy", [rItem.key + "1", rItem.key, rUrl]]
                    ]));
        return _str;
    };

    var __invokeFire = function () {
        if (!__pageLoaded) { return; }
        var _inv = null;
        var _fn = null;
        var _evalStr = "";
        for (var i = 0; i < __invokeList.length; i++) {
            _inv = __invokeList[i];
            _fn = "gStatInvoke.j" + jskitUtil.guid();
            if (_inv.iclass != null) {
                if (_inv.params == null) {
                    _evalStr += (_fn + " = new " + _inv.iclass + "('" + _fn + "');");
                }
            }
            if (_inv.ifuncs != null) {
                var _func = null;
                for (var f = 0; f < _inv.ifuncs.length; f++) {
                    _func = _inv.ifuncs[f];
                    var _action = _fn + "." + _func[0] + "(";
                    for (var j = 0; j < _func[1].length; j++) {
                        if (j > 0) { _action += ","; }
                        _action += "'" + _func[1][j] + "'";
                    }
                    _action += ");";
                }
                _evalStr += _action;
            }
        }
        try {
            eval(_evalStr);
        } catch (e) {
            __msgFunc("Form Action Invoke Exception:$n" + e.message);
        }
    };

    var __display = function () {
        if (__params == null) {
            __loadFormData();
        } else {
            __loadStatData();
        }
    };

    this.reLoad = function () {
        if (__inited) {
            __loadStatData();
        } else {
            __msgFunc("Init not finished!");
        }
        return false;
    };

    this.setChartId = function (v) {
        __chartId = v;
    };
    this.setChartPlayerId = function (v) {
        __chartPlayerId = v;
    };
    this.setChartFileName = function (v) {
        __chartFileName = v;
    };
    this.setStatKey = function (v) {
        __statKey = v;
    };
    this.setFormBoxId = function (v) {
        __formBoxId = v;
    };
    this.setGridBoxId = function (v) {
        __gridBoxId = v;
    };
    var __inited = false;
    var __init = function () {
        if (__params == null) {
            if (__formBoxId == null) {
                __msgFunc("Form Box Id not set,Init failed");
                return;
            }
            __formBox = $("#" + __formBoxId);
            if (__formBox == null) {
                __msgFunc("Invalid form box object");
                return;
            }
        }
        if (__gridBoxId == null) {
            __msgFunc("Grid Box Id not set,Init failed");
            return;
        }
        if (__chartPlayerId == null) {
            __msgFunc("Displayer Box Id not set,Init failed");
            return;
        }
        if (__chartId == null) {
            __msgFunc("ChartId not set,Init failed");
            return;
        }
        if (__statKey == null) {
            __msgFunc("Stat Key not set,Init failed");
            return;
        }

        __gridBox = $("#" + __gridBoxId);
        if (__gridBox == null) {
            __msgFunc("Invalid grid box object");
            return;
        }
        if (__chartFileName == null) {
            __msgFunc("Chart FileName not set,Init failed");
            return;
        }
        __chartPath = "/cellula_client/module/stat/resource/" + __chartFileName + ".swf";
        __inited = true;
    };
    var __pageLoaded = false;
    this.onPageLoad = function () {
        __pageLoaded = true;
        __init();
        __display();
    };

};